<?php
namespace UCenter;

use MediaWiki\Auth\AuthenticationResponse;
use MediaWiki\MediaWikiServices;
use MediaWiki\Session\SessionManager;

class UCenterHooks {
	public const SYNLOGIN_SESSIONKEY = 'isekai_uc_synlogin_url';

    public static function onLoad(\OutputPage $output){
		$sessionManager = SessionManager::getGlobalSession();
		if($sessionManager->exists(self::SYNLOGIN_SESSIONKEY)){ //输出同步登录的脚本
			$output->addModules('ext.ucenter.synlogin');
		}
	}

	public static function addSynloginVars( array &$vars, \OutputPage $out ){
		$sessionManager = SessionManager::getGlobalSession();
		if($sessionManager->exists(self::SYNLOGIN_SESSIONKEY)){
			$vars['ucenterSynloginUrl'] = $sessionManager->get(self::SYNLOGIN_SESSIONKEY);
		}
	}
	
	public static function onLogin($ret, \User $user, $username){
		if(!defined( 'MW_API' )){
			if($ret->status === 'PASS'){
				$uc = new UCenter();
				list($uid, $username, $email) = $uc->uc_get_user($username);
				$context = \RequestContext::getMain();
				$request = $context->getRequest();
				$remember = $request->getVal('wpRemember', 0);
				$ucSynLogin = $uc->uc_user_synlogin($uid, $remember);
				preg_match_all('/src="(?<src>.*?)"/', $ucSynLogin, $matches);
				$urlList = $matches['src'];
				SessionManager::getGlobalSession()->set(self::SYNLOGIN_SESSIONKEY, $urlList);
			}
		}
	}
	
	public static function onLogout($user, &$injected_html){
		if(!defined( 'MW_API' )){
			$uc = new UCenter();
			$injected_html .= $uc->uc_user_synlogout();
		}
	}
	
	public static function onRegister($user){
		$context = \RequestContext::getMain();
		$request = $context->getRequest();
		//print_r($request);
	}
	
	public static function onGetPreferences(\User $user, &$preferences) {
		//var_dump(array_keys($preferences));
		//不允许修改密码
	    if(isset($preferences['password'])){
	        unset($preferences['password']);
	    }

		//不允许修改email
	    if(isset($preferences['emailaddress'])){
	        unset($preferences['emailaddress']);
	    }
		
		//不允许修改email
	    if(isset($preferences['emailauthentication'])){
	        unset($preferences['emailauthentication']);
		}

		//未完成的头像上传插件
		/*
		$uc = new UCenter();
		list($uid, $username, $email) = $uc->uc_get_user($user->getName());
		$avatarLink = $uc->uc_get_avatar_link($uid, 'small');
		//$link = '<a href="' . $uc->uc_change_avatar($uid, 'virtual', false) . '">' . wfMessage('uploadavatar')->text() . '</a>';
		$linkRender = MediaWikiServices::getInstance()->getLinkRenderer();
		$link = $linkRender->makeLink(\SpecialPage::getTitleFor("UploadUserAvatar"), wfMessage('uploaduseravatar')->text());

		$preferences['editavatar'] = array(
			'type' => 'info',
			'raw' => true,
			'label-message' => 'prefs-editavatar',
			'default' => '<img src="' . $avatarLink . '" width="32"></img>&nbsp;' . $link,
			'section' => 'personal/info',
		);

		return true;
		*/
	}
}